//
//  HJSelectGroupMemberController.m
//  KaiChat
//
//  Created by lx on 2023/11/8.
//

#import "HJSelectGroupMemberController.h"
#import "HJNavigationController.h"
#import "HJGroupSelectMemberCell.h"
#import "HJSectionHeaderView.h"
#import "HJIM.h"
#import "HJUserInfoController.h"
#import "QMUITextField.h"
#import "HJSelectMemberView.h"
#import "HJChatGroupModel.h"
#import "TJEmptyDataHandler.h"
#import "HJOrderedDictionary.h"
#import "HJSearchView.h"
#import "UITableView+SCIndexView.h"

@interface HJSelectGroupMemberController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSMutableArray *sortKeys;
@property (nonatomic, strong) NSMutableArray *searchDatas;
@property (nonatomic, strong) HJOrderedDictionary *userDict;

@property (nonatomic, strong) NSArray *originalDatas;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;

@property (nonatomic, weak) HJSelectMemberView *selectMemberView;
@property (nonatomic, weak) HJBarButton *doneButton;
@property (nonatomic, weak) UIView *searchView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, assign) NSInteger lastCount;
@property (nonatomic, weak) QMUITextField *textField;
@property (nonatomic, assign) NSInteger enabledCount;
@property (nonatomic, assign) NSInteger count;



@end

@implementation HJSelectGroupMemberController

- (void)showInController:(UIViewController *)controller {
    HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:self];
    [controller presentViewController:navController animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    

    
    self.count = 0;
    HJBarButton *doneButton = [HJBarButton barButtonWithTitle:@"Done" color:UIColor.tj_mainColor target:self action:@selector(didClickDoneButton:)];
    doneButton.enabled = NO;
    [doneButton setTitleColor:UIColor.tj_mainColor forState:UIControlStateNormal];
    [doneButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
    [self.navigationBar.contentView addSubview:doneButton];
    [doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.offset(40);
        make.centerY.offset(0);
        make.height.offset(40);
    }];
    _doneButton = doneButton;
    
    UIView *headerView = [UIView addToView:self.view];
    headerView.backgroundColor = UIColor.whiteColor;
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(KNavBarHight);
        make.height.offset(60);
    }];
    
    HJSearchView *searchView = [HJSearchView addToView:headerView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(10);
        make.height.offset(40);
    }];
 
    QMUITextField *textField = searchView.textField;
    textField.placeholder = @"Search";
    textField.maximumTextLength = 20;
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _textField = textField;
    
    TJWeakify(self)
    HJSelectMemberView *selectMemberView = [HJSelectMemberView addToView:headerView];
    [selectMemberView setDidClickDeleteButtonBlock:^(HJGroupMemberModel * _Nonnull model) {
        [weakself didSelectRowWithModel:model];
    }];
    [selectMemberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(0);
        make.top.equalTo(searchView.mas_bottom).offset(10);
    }];
    
    _headerView = headerView;
    _selectMemberView = selectMemberView;
    _searchView = searchView;
    
    
    if (_type == HJSelectGroupMemberTypeRemoveMember) {
        self.enabledCount = 1;
        self.navigationBar.title = @"Cancel Members";
    } else {
        self.enabledCount = 1;
        self.navigationBar.title = @"Select Administrator";
    }
    
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.1)];
    [self.tableView registerClass:HJGroupSelectMemberCell.class forCellReuseIdentifier:@"HJGroupSelectMemberCell"];
    [self.tableView registerClass:HJSectionHeaderView.class forHeaderFooterViewReuseIdentifier:@"HJSectionHeaderView"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 64;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSectionIndexColor:UIColor.tj_9B9B9BColor];
    
    SCIndexViewConfiguration *configuration = [SCIndexViewConfiguration configuration];
    configuration.indicatorBackgroundColor = UIColor.tj_mainColor;
    configuration.indicatorTextFont = UIFontMediumMake(20);
    configuration.indexItemTextColor = UIColor.tj_BEBDCAColor;
    configuration.indexItemTextFont = UIFontMediumMake(12);
    configuration.indexItemSelectedTextFont = UIFontMediumMake(12);
    configuration.indexItemSelectedTextColor = UIColor.tj_BEBDCAColor;
    configuration.indexItemSelectedBackgroundColor = UIColor.clearColor;
    self.tableView.sc_indexViewConfiguration = configuration;
    self.tableView.sc_translucentForTableViewInNavigationBar = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView.mas_bottom);
        make.left.right.bottom.offset(0);
    }];
    
    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView];
    [self loadData];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    
    NSString *keyword = textField.text;
    
    if (isEmptyString(keyword)) {
        for (HJGroupMemberModel *obj in self.originalDatas) {
            obj.nicknameAttributedstring = nil;
        }
        self.emptyDataHandler.canDisplay = YES;
        [self.searchDatas removeAllObjects];
        [self handleModels:self.originalDatas];
        return;
    }
    
    self.emptyDataHandler.canDisplay = NO;
    [self.searchDatas removeAllObjects];
    for (HJGroupMemberModel *obj in self.originalDatas) {
        NSRange range = [obj.nickname rangeOfString:keyword options:NSCaseInsensitiveSearch];
        if (range.location != NSNotFound) {
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:obj.nickname];
            [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.tj_mainColor range:range];
            obj.nicknameAttributedstring = attrStr;
            [self.searchDatas addObject:obj];
        } else {
            obj.nicknameAttributedstring = nil;
        }
    }
    [self handleModels:self.searchDatas];
}

- (void)didClickDoneButton:(UIButton *)button {
    
    [HJHUD showLoadingInView:self.view];
 
    if (_type == HJSelectGroupMemberTypeRemoveMember) {
        [HJIM.shareIM.groupManager removeGroupMemberByGroupId:self.groupId userIds:self.userDict.allKeys completion:^(NSError * _Nullable error) {
            if (error) {
                [HJHUD showErrorMessageTip];
                return;
            };
            
            if (self.complete) {
                self.complete();
            }
            [self dismissToRootViewController:YES completion:nil];
            [HJHUD showSucceedMessageTip];
        }];
        return;
    }
    
    if (_type == HJSelectGroupMemberTypeAddManager) {
        [HJIM.shareIM.groupManager addGroupManagerByGroupId:self.groupId userIds:self.userDict.allKeys completion:^(NSError * _Nullable error) {
            if (error) {
                if (error.code == 1602) {
                    [HJHUD showErrorMessage:error.localizedFailureReason];
                } else {
                    [HJHUD showErrorMessageTip];
                }
                return;
            };
            
            if (self.complete) {
                self.complete();
            }
            [self dismissToRootViewController:YES completion:nil];
            [HJHUD showSucceedMessageTip];
        }];
    }
 
}

- (void)didClickNewFriendButton {
    [self.navigationController pushViewControllerWithName:@"HJApplyListController"];
}
 
- (nullable HJGroupSelectMemberCell *)getVisibleCellWithModel:(HJGroupMemberModel *)model {
    for (HJGroupSelectMemberCell *cell in self.tableView.visibleCells) {
        if (cell.model == model) {
            return cell;
        }
    }
    return nil;
}


- (void)loadData {
    [[HJIM shareIM].groupManager queryGroupMemberListWithGroupId:self.groupId completion:^(NSArray<HJGroupMemberModel *> * _Nullable datas) {
        self.originalDatas = datas;
        
        NSMutableArray *notJoinDatas = [NSMutableArray array];
        for (HJGroupMemberModel *model in datas) {
            [notJoinDatas addObject:model];
        }
        
        dispatch_async_main_queue(^{
            self.emptyDataHandler.canDisplay = YES;
            [self hiddenLoading];
            [self handleModels:notJoinDatas];
        });
    }];
}
 
- (void)updateSelectState:(HJGroupMemberModel *)obj {
    HJGroupMemberModel *addMemberModel = [self.userDict objectForKey:obj.userId];
    obj.isSelect = addMemberModel.isSelect;
    if (obj.isSelect) {
        [self.userDict setObject:obj forKey:obj.userId];
    }
}

- (void)handleModels:(NSArray *)models {
    
    NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
    
    for (HJGroupMemberModel *obj in models) {
        
        if (obj.role == 1 || obj.role == 2) {
            _count = _count + 1;
        }
        
        if (TJIM_isSelf(obj.userId)) {
            continue;
        }
        
        //添加管理员只能添加普通成员
        if (_type == HJSelectGroupMemberTypeAddManager && (obj.role == 1 || obj.role == 2)) {
            continue;
        }
        
        //管理员不能踢群主和管理员
        if (_type == HJSelectGroupMemberTypeRemoveMember && self.role.intValue == 2 && (obj.role == 1 || obj.role == 2)) {
            continue;
        }
        
        [self updateSelectState:obj];
        
        NSString *displayName = obj.nickname;
        NSString *firstLetter = [displayName.firstPinYin uppercaseString];
        if (firstLetter.length == 0 || !isalpha([firstLetter characterAtIndex:0])) {
            firstLetter = @"#";
        }
        NSMutableArray *dictMarr = [mainDict valueForKey:firstLetter];
        if (!dictMarr) {
            [mainDict setValue:[NSMutableArray array] forKey:firstLetter];
            dictMarr = [mainDict valueForKey:firstLetter];
        }
        [dictMarr addObject:obj];
    }
    
    NSArray *nonameList = [mainDict valueForKey:@"#"];
    if (nonameList) {
        [mainDict removeObjectForKey:@"#"];
    }
    
    [self.datas removeAllObjects];
    [self.sortKeys removeAllObjects];
    
    NSArray *sortKeys = [mainDict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull obj1, NSString *  _Nonnull obj2) {
        return [obj1 compare:obj2] == NSOrderedDescending;
    }];
 
    [sortKeys enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.datas addObject:@{ @"title": obj, @"datas": mainDict[obj]}];
    }];
    
    self.sortKeys = [NSMutableArray arrayWithArray:sortKeys];
    if (nonameList.count) {
        [self.sortKeys addObject:@"#"];
        [self.datas addObject:@{@"title": @"#", @"datas": nonameList}];
    }
    
    self.tableView.sc_indexViewDataSource = self.sortKeys;
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *datas = self.datas[section][@"datas"];
    return [datas count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJGroupSelectMemberCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJGroupSelectMemberCell" forIndexPath:indexPath];
    HJGroupMemberModel *model = self.datas[indexPath.section][@"datas"][indexPath.row];
    model.isLookInfo = YES;
    cell.model = model;
    TJWeakify(self)
    [cell setDidClickInfoButtonBlock:^{
        HJUserInfoController *infoController = [[HJUserInfoController alloc] init];
        infoController.userId = model.userId;
        [weakself.navigationController pushViewController:infoController];
    }];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJGroupMemberModel *model = self.datas[indexPath.section][@"datas"][indexPath.row];

    if (_type == HJSelectGroupMemberTypeAddManager) {
        if (!model.isSelect && self.userDict.count + _count > 8) {
            [HJHUD showErrorMessage:@"Only set up 8 adminstrtors"];
            return;
        }
    }

    [self didSelectRowWithModel:model];
}

- (void)didSelectRowWithModel:(HJGroupMemberModel *)model {
    
    model.isSelect = !model.isSelect;
    
    HJGroupSelectMemberCell *cell = [self getVisibleCellWithModel:model];
    cell.model = model;
    if (model.isSelect) {
        [self.userDict setObject:model forKey:model.userId];
    } else {
        [self.userDict removeObjectForKey:model.userId];
    }
    
    [self updateDoneTitle];
    [self updateSelectMemberViewHeight];
}


- (void)updateSelectMemberViewHeight {

    execute(^{
        if (self.userDict.count > 0) {
            [self.headerView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(140);
            }];
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(80);
                make.top.equalTo(self.searchView.mas_bottom).offset(10);
            }];
        } else {
            [self.headerView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(60);
            }];
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(0);
                make.top.equalTo(self.searchView.mas_bottom).offset(10);
            }];;
        }
    }, ^{
        self.selectMemberView.datas = self.userDict.allValues;
    });
}

- (void)updateDoneTitle {
    if (self.userDict.count > 0) {
        _doneButton.enabled = self.userDict.count >= _enabledCount;
        [_doneButton setTitle:[NSString stringWithFormat:@"Done(%ld)", self.userDict.count] forState:UIControlStateNormal];
    } else {
        _doneButton.enabled = NO;
        [_doneButton setTitle:@"Done" forState:UIControlStateNormal];
    }
    [_doneButton sizeToFit];
    CGFloat doneButtonW = MAX(_doneButton.tj_width + 10, 40);
    [_doneButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.offset(doneButtonW);
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HJSectionHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HJSectionHeaderView"];
    view.titleLabel.text = @"";
    view.contentView.backgroundColor = UIColor.tj_F6F6F6Color;
    view.backgroundColor = UIColor.tj_F6F6F6Color;
    NSString *sectionTitle = self.datas[section][@"title"];
    view.titleLabel.text = sectionTitle;
    view.titleLabel.textColor = UIColor.tj_BEBDCAColor;
    view.titleLabel.font = UIFontMake(12);
    return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColor.clearColor;
    return view;
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSMutableArray *)sortKeys {
    if (!_sortKeys) {
        _sortKeys = [NSMutableArray array];
    }
    return _sortKeys;
}

- (HJOrderedDictionary *)userDict {
    if (!_userDict) {
        _userDict = [HJOrderedDictionary dictionary];
    }
    return _userDict;
}
 

- (NSMutableArray *)searchDatas {
    if (!_searchDatas) {
        _searchDatas = [NSMutableArray array];
    }
    return _searchDatas;
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}



@end

 
